package com.zhangjk.service.impl;



import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhangjk.enums.AppConstant;
import com.zhangjk.enums.ResultEnum;

import com.zhangjk.exception.CheckException;
import com.zhangjk.mapper.PictureMapper;
import com.zhangjk.mapper.UserMapper;
import com.zhangjk.pojo.Picture;
import com.zhangjk.pojo.User;
import com.zhangjk.pojo.userVo.UserOrderNum;
import com.zhangjk.pojo.userVo.UserOrderNumQuery;
import com.zhangjk.pojo.userVo.UserVo;
import com.zhangjk.pojo.userVo.userDto;
import com.zhangjk.service.UserService;

import com.zhangjk.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;



/**
 * Created by zhangjk on 2019/4/21.
 */
@Service
public class UserServiceImpl implements UserService {

private   static  final Logger  loger= LoggerFactory.getLogger(UserServiceImpl.class);

private   static  final   String   Manger_session_key="fsdfdrt3q4523413223123";


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PictureMapper pictureMapper;


    @Autowired
    private   DateProvider  dateProvider;

    @Autowired
    private   UserInfoUtil  userInfoUtil;

    /**
     *   小程序登录
     * @param userVo
     * @param request
     * @return
     */
    @Override
    public Boolean SaveUser(UserVo userVo,String openid) {
        try {
//            JwtToken  jwtToken=    userInfoUtil.getUserInfo();
            User  user=new User();

            user.setCreatetime(dateProvider.getCurrentTime());
            user.setOpenid(openid);
            user.setImgUrl(userVo.getAvatarUrl());
            if (userVo.getGender().equals("1")){
                user.setSex("女");
            }else  if (userVo.getGender().equals("2")){
                user.setSex("男");
            }
            user.setName(userVo.getNickName());
            BeanNotNullUtil.init(user);
            userMapper.insert(user);
            return   true;
        }catch (Exception e){
           loger.error(e.getMessage());
              return   false;
        }

    }


    /**
     * 查询当前的openid之前有没有在数据库绑定过
     * @param openid
     * @return
     */
    @Override
    public User findbyopenid(String openid) {
        return userMapper.findbyopenid(openid);
    }

    @Override
    public ResponseMessage login(String code, String password) {
        ResponseMessage  responseMessage=new ResponseMessage();
        User  user=   userMapper.login(code,password);
        TokenUtil tokenUtil = new TokenUtil();
        JwtToken    jwtToken = new JwtToken();
        if (user!=null){
            jwtToken.setOpenid(user.getOpenid());
            jwtToken.setSession_key(Manger_session_key);
            jwtToken.setExpiration(new Date());
          String    token = tokenUtil.createJwtString(jwtToken);
            responseMessage.setStatus(0);
            responseMessage.setResult(token);
            responseMessage.setMessage("登陆成功");

        }else {
            responseMessage.setStatus(1);
            responseMessage.setResult("");
            responseMessage.setMessage("登录失败");
        }
        return responseMessage;
    }




    /**
     * 绑定手机号
     * @param phone
     * @param code
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public ResponseMessage RegisterPhone(String phone, String code, HttpServletRequest request) throws  Exception {

        ResponseMessage  responseMessage=new ResponseMessage();
        String   messagecode = request.getHeader(AppConstant.Rande_Code);
        String[] message = messagecode.split("#");
        Date date = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String registerdate = sdf.format(date);
        Boolean checkdataresult = DateUtil.CompareValidateTime(sdf.parse(URLDecoder.decode(message[1])), sdf.parse(registerdate));

        JwtToken  jwtToken=  userInfoUtil.getUserInfo();

        if (code.equals(message[0])
                && checkdataresult){

            userMapper.updatePhoneByopenid(Long.valueOf(phone),jwtToken.getOpenid());

            responseMessage.setStatus(0);
            responseMessage.setResult("");
            responseMessage.setMessage("成功");


        }else {

            responseMessage.setStatus(1);
            responseMessage.setResult("");
            responseMessage.setMessage("验证码错误或者超时");

        }

return responseMessage;

    }



    @Override
    public Object getUser(String userId) {
        return ResultVOUtil.success(userMapper.findById(Integer.parseInt(userId)));
    }

    /**
     * 更改用户相关信息
     * @param usr
     * @param request
     * @return
     */
    @Override
    public Object UpdateUser(User usr,HttpServletRequest request) {

        userDto ud=new userDto();
         // 从token 里面获取到相关用户
        JwtToken  jwtToken=  userInfoUtil.getUserInfo();
        // 根据openid 获取到当前用户的全部信息
        User   user=   userMapper.findbyopenid(jwtToken.getOpenid());

        // 这个是可以更改用户的头像地址和 昵称的
        user.setName(usr.getName());
        Picture  picture=pictureMapper.findAllByCreatecodeAndLx(user.getId().toString(),"1","0");
        if (picture!=null){
           String   host="http://47.104.86.228:8001";
            System.out.println(request.getServerName());
            user.setImgUrl(host+"/"+picture.getImgname());
            picture.setState(1L);
            pictureMapper.updateByPrimaryKey(picture);
        }
        userMapper.updateByPrimaryKeySelective(user);//更新用户表
        return ResultVOUtil.success(user.getImgUrl());
    }

    /**
     * 用户列表---查询用户，姓名，电话，车牌，参与订单次数等等信息
     * @param query
     * @param request
     * @return
     */
    @Override
    public  PageInfo<UserOrderNum> serarchUser(UserOrderNumQuery query, HttpServletRequest request) {

        PageHelper.startPage(query.getPageIndex(), query.getPageSize());
        return new PageInfo<>(userMapper.findByAllOrderNum(query.getUser()));
    }


    /**
     * 删除 --用户
     * @param UserId
     * @return
     */
    @Override
    public Object deleteUserById(Integer UserId) {
        int i = userMapper.deleteByPrimaryKey(UserId);
        if(i>0){
            return ResultVOUtil.success();
        }
        return ResultVOUtil.error(1003,"删除失败！");
    }


    /**
     * 修改--y用户信息
     * @param usr
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public Object updateUser(User usr, HttpServletRequest request) throws Exception {
        if(usr.getId()==null || usr.getId()<1){
                throw  new CheckException(ResultEnum.PARAM_ERROR_ID);
        }
        usr.setUpdatetime(dateProvider.getCurrentTime());
        int i = userMapper.updateByPrimaryKeySelective(usr);
        if(i>0){
            return ResultVOUtil.success();
        }
        return ResultVOUtil.error(1004,"修改失败！");
    }


    /**
     * 修改用户状态
     * @param UserId
     * @param state
     * @return
     */
    @Override
    public Object updateState(Integer UserId, String state) {
        User usr=new User();
        usr.setId(UserId);
        usr.setState(Integer.parseInt(state));
        usr.setUpdatetime(new Date());

        usr.setUpdatetime(DataUtil.getData());

        int i = userMapper.updateByPrimaryKeySelective(usr);
        if(i>0){
            return ResultVOUtil.success();
        }
        return ResultVOUtil.error(1004,"修改失败！");
    }


}
